package com.csx.orm.mybatisplus.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csx.orm.mybatisplus.entity.User;
import com.csx.orm.mybatisplus.entity.dto.UserQueryCondition;
import com.csx.orm.mybatisplus.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Autowired
    private UserMapper userMapper;

    public List<User> getAllUsers() {
        return userMapper.selectList(null);
    }

    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    public void createUser(User user) {
        userMapper.insert(user);
    }

    public void updateUser(User user) {
        userMapper.update(user, null);
    }

    public void deleteUser(Long id) {
        userMapper.deleteById(id);
    }

    public int countUser(String firstName) {
        return Math.toIntExact(userMapper.selectCount(Wrappers.<User>lambdaQuery()
                .eq(User::getFirstName, firstName)));
    }

    public List<User> getUserListByCondition(String firstName, int size) {
        Page<User> page = new Page<>(1, size);
        Page<User> userPage = userMapper.selectPage(page, Wrappers.<User>lambdaQuery()
                .eq(User::getFirstName, firstName));
        return userPage.getRecords();
    }

    public List<User> getUserConditional(UserQueryCondition condition) {
        Page<User> page = new Page<>(1, 10);
        LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>lambdaQuery()
                .eq(StringUtils.isNotBlank(condition.getFirstName()), User::getFirstName, condition.getFirstName())
                .eq(StringUtils.isNotBlank(condition.getLastName()), User::getLastName, condition.getLastName())
                .eq(StringUtils.isNotBlank(condition.getType()), User::getType, User.Type.valueOf(condition.getType()));
        return page(page,queryWrapper).getRecords();
    }
}
